import minecraft_launcher_lib
import os
from setting import (
    VERSION,
    MINECRAFT_DIR,
)  # 你可能需要调整这个导入语句，确保正确导入 VERSION
import subprocess
from datetime import datetime
import winreg


class launcher:
    def gameStart(self, player_name, minecraft_dir, minecraft_version, JVM, JavaPath):
        options = minecraft_launcher_lib.utils.generate_test_options()
        Xmx = "-Xmx" + JVM
        player_name = str(player_name)
        # 设置选项
        options["jvmArguments"] = [Xmx]
        options["username"] = player_name
        options["executablePath"] = JavaPath
        options["launcherName"] = "cookiebox"
        options["launcherVersion"] = VERSION  # 请确保 VERSION 变量已定义
        # 生成启动命令
        minecraft_command = minecraft_launcher_lib.command.get_minecraft_command(
            minecraft_version, minecraft_dir, options
        )
        print(minecraft_command)
        # 执行启动命令

        now = datetime.now()

        # 格式化为字符串
        timestamp_str = now.strftime("%Y-%m-%d和%H-%M-%S")

        # 要创建的文件路径
        file_path = os.path.join(
            MINECRAFT_DIR, minecraft_version + "-" + timestamp_str + "minecraft.log"
        )

        # 打开日志文件以便写入
        with open(
            MINECRAFT_DIR
            + "\\"
            + minecraft_version
            + "-"
            + timestamp_str
            + "minecraft.log",
            "w",
        ) as log:
            # 使用 subprocess.run() 启动 Minecraft，并将标准输出和标准错误重定向到日志文件
            result = subprocess.run(
                minecraft_command, stdout=log, stderr=subprocess.STDOUT
            )
        # subprocess.run(minecraft_command)
        return result.returncode

    def getVersionList(self):
        # 获取本地版本
        dir = MINECRAFT_DIR + "\\" + "versions"
        print(dir)
        if os.path.isdir(dir):
            for root, dirs, files in os.walk(dir):
                return dirs
        else:
            return []

    def getVersionModsList(self, version):
        dir = MINECRAFT_DIR + "\\" + "versions\\" + version + "\\mods"
        print(dir)
        if os.path.isdir(dir):
            for root, dirs, files in os.walk(dir):
                return dirs
        else:
            return []

    def getJavaInfo(self):
        java_info = []

        # Function to scan Java installations in given registry path
        def scan_java_installations(reg_path):
            try:
                key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, reg_path)
                i = 0
                while True:
                    subkey_name = winreg.EnumKey(key, i)
                    subkey_path = f"{reg_path}\\{subkey_name}"
                    subkey = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, subkey_path)
                    version, _ = winreg.QueryValueEx(subkey, "JavaHome")
                    java_info.append({"version": subkey_name, "path": version})
                    i += 1
            except FileNotFoundError:
                pass
            except OSError:
                pass

        # Scan both JDK and JRE installations
        scan_java_installations(r"SOFTWARE\\JavaSoft\\Java Development Kit")
        scan_java_installations(r"SOFTWARE\\JavaSoft\\Java Runtime Environment")

        return java_info


launcher1 = launcher()
# 调用 gameStart 方法来启动游戏
# returncode = luncher.gameStart(
#     "weilaiwno",  # 玩家名称
#     "F:\\.minecraft",  # Minecraft 目录
#     "1.21",  # Minecraft 版本
#     "1G",  # JVM 内存分配
#     "C:\\Users\\Administrator\\AppData\\Roaming\\.minecraft\\cache\\java\\java-runtime-delta\\windows-x64\\java-runtime-delta\\bin\\java.exe",  # Java 可执行文件路径
# )
# print("Minecraft 启动完成，退出码:", returncode)

print(launcher1.getVersionList())

print(launcher1.getVersionModsList("1.21"))

print(launcher1.getJavaInfo())
